package com.test.atomic;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountDownLatchDemo {
    public static void main(String[] args) {
        //假设有3个模块需要预先加载
        CountDownLatch countDownLatch=new CountDownLatch(3);
        //主任务
        new Thread(()->{
            try {
                System.out.println("等待数据加载...");
                System.out.println(String.format("还有%d个前置任务",countDownLatch.getCount()));
                countDownLatch.await();
                System.out.println("数据加载完毕，正式开始游戏");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(new preTaskThread("加载地图数据",countDownLatch)).start();
        new Thread(new preTaskThread("加载人物模型",countDownLatch)).start();
        new Thread(new preTaskThread("加载背景音乐",countDownLatch)).start();

    }
    static class preTaskThread implements  Runnable{
        private String task;
        private CountDownLatch countDownLatch;

        public preTaskThread(String task, CountDownLatch countDownLatch) {
            this.task = task;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                Random random=new Random();
                Thread.sleep(random.nextInt(1000));
                System.out.println(task+"--任务完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();

            }
        }

    }
}
